<template>
  <div id="app">
    <el-card shadow="always">
      {{staffSearch}}
      <!--条件查询-->
      <el-form :inline="true" size="medium" :model="staffSearch" class="demo-form-inline">
        <el-form-item >
          <el-input v-model="staffSearch.id" placeholder="员工"></el-input>
        </el-form-item>
        <el-form-item >
          <el-input v-model="staffSearch.ename" placeholder="员工姓名"></el-input>
        </el-form-item>
        <el-form-item >
          <el-select v-model="staffSearch.departmentId" placeholder="所在部门">
            <el-option label="所在部门" value="0"></el-option>
            <el-option :label="d.departmentName" :value="d.departmentId" v-for="d in departmentsList" :key="d.departmentId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="search" icon="el-icon-search">查询</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" plain @click="AddSaff" icon="el-icon-plus">添加</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" plain @click="handleDelete" icon="el-icon-remove">批量删除</el-button>
        </el-form-item>
      </el-form>

      <el-table
              :data="staffList"
              style="width: 100%"
              @selection-change="handleSelectionChange">
        <el-table-column
                type="selection">
        </el-table-column>
        <el-table-column
                label="员工ID"
                align="center"
                prop="id"
                width="180"/>
        <el-table-column
                label="员工姓名"
                align="center"
                prop="ename"/>

        <el-table-column
                label="员工email"
                align="center"
                prop="email"/>
        <el-table-column
                label="员工电话"
                align="center"
                prop="phoneNumber"/>
        <el-table-column
                label="入职时间"
                align="center"
                prop="hireDate"/>
        <el-table-column
                label="所在部门"
                align="center"
                prop="departmentName"/>
        <el-table-column
                align="right">
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                      size="mini"
                      @click="handleEdit(scope.$index, scope.row)">Edit</el-button>
              <el-button
                      size="mini"
                      type="danger"
                      @click="handleDelete(scope.$index, scope.row)">Delete</el-button>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>

      <!--分页导航-->
      <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
      </el-pagination>
    </el-card>

    <!--对话框 (添加修改员工信息)-->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
      {{staff}}
      <el-form :model="staff" :rules="rules" ref="ruleForm">
        <el-form-item label="员工姓名" prop="sname" :label-width="formLabelWidth">
          <el-input v-model="staff.ename" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="员工email" prop="email" :label-width="formLabelWidth">
          <el-input v-model.number="staff.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工电话" prop="addr" :label-width="formLabelWidth">
          <el-input v-model="staff.phoneNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所学部门" prop="cid" :label-width="formLabelWidth" style="width: 1200px">
          <el-select v-model="staff.departmentId" placeholder="请选择所在部门" >
            <el-option label="所有部门" value="0"></el-option>
            <el-option :label="d.departmentName" :value="d.departmentId" v-for="d in departmentsList" :key="d.departmentId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveStaff">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import staffApi from "@/api/staff"
  import departmentsApi from "@/api/departments"
  export default {
    data() {

      return {
        staffList: [],
        page: 1,               // 当前页
        pageSize: 5,           // 每页大小
        total: 100,            // 总记录数
        staffSearch: {},
        departmentsList:{},
        staff:{},
        dialogFormVisible:false,//不显示对话框
        title:'Add Staff',//对话框标题
        formLabelWidth:'100px',//对话框宽度
        multipleSelection:[], //选中多项
        eids:[],
      }
    },
    created() {
      // this.findAllStaff()
      // this.findByPage(this.page, this.pageSize)
      this.search()
      this.findAllDepartments()
    },
    methods: {
      //查询所有员工信息
      async findAllStaff() {
        const {data: res} = await staffApi.findAllStaff()

        if (res.code == 200) {
          this.staffList = res.data.list
        }
      },
      // 员工信息的分页查询
      async findByPage() {
        const {data: res} = await staffApi.findByPage(this.page, this.pageSize)
        console.log(res)
        if (res.code === 200) {
          this.staffList = res.data.pr.rows
          this.total = res.data.pr.total
        }
      },

      async findAllDepartments() {
        const {data: res} = await departmentsApi.findAllDepartments()
        console.log(res)
        if (res.code == 200) {
          this.departmentsList = res.data.list
        }
      },
      //员工信息的条件查询带分页
      async search() {
        const {data: res} = await staffApi.search(this.page, this.pageSize, this.staffSearch)
        console.log(res)
        if (res.code === 200) {
          this.staffList = res.data.pr.rows
          this.total = res.data.pr.total
        }
      },
      async AddStaff() {//添加员工信息
        //修改对话框标题
        this.title = 'AddStaff'
        //清空会话框内
        this.staff = {}
        //打开对话框
        this.dialogFormVisible = true
      },
      async saveStaff() {
        this.$refs.ruleForm.validate(async valid => {
          let url = "/staff/add"//默认添加员工信息
          let method = "post"//添加是post请求
          if (this.staff.id) {
            url = "/staff/update"//如果sid有值是修改员工信息
            method = "put"//修改是put请求
          }
          //向后端发送请求，添加或者修改员工信息
          if (valid) {
            const {data: res} = await staffApi.save(url, method, this.staff)
            console.log("res:", res)
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: res.message,
                onClose: () => {        // 关闭对话框时的回调，查询新的员工信息
                  // 关闭对话框
                  this.dialogFormVisible = false
                  // 重新查询员工信息
                  this.search()
                }
              })
            } else { // 后端执行失败时返回500
              this.$message({
                type: 'error',
                message: res.message
              })
            }
            // console.log("验证成功")
          } else {
            console.log("验证失败!!!")
            return false
          }
        })
      },
      handleSizeChange(val) {
        this.multipleSelection = val;

      },
      handleEdit(index, row) {
        //修改对话框标题
        this.title = 'EditStaff'
        //显示需要修改的员工信息到对话框
        this.staff = row
        //打开对话框
        this.dialogFormVisible = true
        console.log(index, row);
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        console.log(this.multipleSelection)
      },
      // 每页大小改变时事件
      handleSizeChange(index,row) {
        this.pageSize = val
        // this.findByPage()
        this.search()
        console.log(`每页 ${val} 条`);
      },
      // 当前页改变时事件
      handleCurrentChange(val) {
        this.page = val
        // this.findByPage()
        this.search()
        console.log(`当前页: ${val}`);
      },
      //单个删除或者批量删除员工信息
      handleDelete(index, row) {
        this.eids = []
        if(row){//row有值，代表删除单条员工信息
          this.eids.push(row.id)
        }else{
          this.eids = this.multipleSelection.map(m=>m.id)
        }
        this.$confirm(`是否确定删除学号为${this.eids}的员工信息吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let _this = this
          staffApi.deleteSaff(this.eids)
                  .then(({data:res}) => {
                    console.log("res:",res)
                    if (res.code === 200) {
                      this.$message({
                        type: 'success',
                        message: res.message,
                        onClose: () => {
                          // 重新加载数据
                          _this.search()
                        }
                      })
                    } else {
                      this.$message({
                        type: 'error',
                        message: res.message
                      })
                    }

                  })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    }
  }

</script>

<style>
  #app{
    diaplay:flex;
    justify-content: center;
  }
  .el-card{
    margin-left: 40px;
    margin-right: 40px;
  }

</style>
